//
//  ConfigManager.swift
//  TimeBoat
//
//  Created by Jun on 2022/9/19.
//  Copyright © 2022 Time Boat. All rights reserved.
//

import Foundation

@objc class ConfigManager: NSObject {
    @objc static let shared = ConfigManager()
    
    private let TAG = LogTag.init(rawValue: "ConfigManager")
    private var mTimer: Timer? = nil
    public var mConfigInfoData: ConfigInfoQueryData? = nil
    
    public func start() {
        Log.debug(tag: TAG, "start")
        
        createTimer()
        addObserverHandle()
        
        getConfigInfo()
    }
    
    public func getSupportBLENameList() -> [String] {
        var list: [String] = [String]()
        
        if nil != mConfigInfoData && nil != mConfigInfoData!.bleName {
            let bleName: String = mConfigInfoData!.bleName!
            
            list = bleName.components(separatedBy: ",")
        }
        
        if list.count <= 0 {
            list.append("QT20")
        }
        
        return list
    }
    
    public func getHeartBeatTimeInterval() -> UInt16 {
        var interval: UInt16 = 30
        
        if nil != mConfigInfoData && mConfigInfoData!.heartBeatInterval > 0 {
            interval = mConfigInfoData!.heartBeatInterval
        }
        
        return interval
    }
    
    public func getTCPHost() -> String {
        var host = "smart-tcp-test.glxsystem.com"
        
        if nil != mConfigInfoData && nil != mConfigInfoData!.tcpHost {
            host = mConfigInfoData!.tcpHost!
        }
        
        return host
    }
    
    public func getTCPPort() -> UInt16 {
        var port: UInt16 = 10100
        
        if nil != mConfigInfoData && mConfigInfoData!.tcpPort > 0 {
            port = mConfigInfoData!.tcpPort
        }
        
        return port
    }
    
    
    private func addObserverHandle() {
        NotificationCenter.default.addObserver(self, selector: #selector(onAppDidBecomeActiveHandle), name: UIApplication.didBecomeActiveNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(onAppDidLoginHandle), name: .userDidLogin, object: nil)
    }
    
    @objc func onAppDidBecomeActiveHandle() {
        Log.debug(tag: TAG, "app did become active handle")
        
        getConfigInfo()
    }
    
    @objc func onAppDidLoginHandle() {
        Log.debug(tag: TAG, "app did login handle")
        
        getConfigInfo()
    }
    
    private func createTimer() {
        if nil == mTimer {
            mTimer = Timer.scheduledTimer(timeInterval: 3*60, target: self, selector: #selector(timerHandle), userInfo: self, repeats: true)
            RunLoop.main.add(mTimer!, forMode: .common)
        }
    }
    
    @objc func timerHandle() {
        Log.debug(tag: TAG, "timer handle")
        
        getConfigInfo()
    }
    
    @discardableResult
    private func queryConfigInfo(completion: APICompletion<ConfigInfoQueryData>? = nil) -> APITASK? {
        var params = [String: Any]()
        
        let token = AccountManager.shareAccount().token()
        if (nil != token) {
            params["token"] = token
        }

        params["os"] = "ios"
        params["versionCode"] = Bundle.main.infoDictionary?["CFBundleVersion"]
        params["versionName"] = Bundle.main.infoDictionary?["CFBundleShortVersionString"]
        return API.POST("config-info/query", params, completion)
    }
    
    private func getConfigInfo() {
        queryConfigInfo() { [weak self] result  in
            if result.suc {
                self?.mConfigInfoData = result.data
            }
        }
    }
    
    private func configInfoHandle(data: ConfigInfoQueryData) {
        if data.versionExpired > 0 {
            DispatchQueue.main.async {
                self.showAppExpired()
            }
        }
    }
    
    private func showAppExpired() {
        let alertVC = UIAlertController.init(title: "提示", message: "该版本已过期，请下载最新版本！", preferredStyle: .alert)
        alertVC.addAction(UIAlertAction.init(title: "确定", style: .destructive, handler: { action in
            Log.debug("click confirm")
            exit(0)
        }))
        
        AppDelegate.shared.window?.rootViewController?.present(alertVC, animated: true)
    }
}
